
const int YaliPin = A0; // 定义水压输入引脚
const int trigPin = 5;  // 定义触发引脚，连接到超声波模块的Trig脚
const int echoPin = 4;  // 定义回声引脚，连接到超声波模块的Echo脚

float Distance = 0;
float averageValue = 0;
unsigned long preHeartTick_B = 0;
unsigned long lasTemperatureReadTick = 0;

void sendtoUDPServer();
void receiveTCPServerB(String TcpClient_Buff);
bool check_and_convert_sum_change(int var1, int var2, int var3);
void Chuanganqi();
void setupSystemB();
void loopSystemB();

void receiveTCPServerB(String TcpClient_Buff)
{
    int a = TcpClient_Buff.indexOf("msg=");
    if (TcpClient_Buff.indexOf("f5") > 0)
    {
        sendtoUDPServer(); // 发送UDP消息
    }
    else if (a > 0)
    {
        a = a + 4;
        int b = 0, d = 0, e = 0;
        String c = "";
        char ch[] = ".";
        while (int(TcpClient_Buff.length()) > e)
        {
            b = TcpClient_Buff.indexOf("=", a) + 1;
            if (b - a > 2)
            {
                c = TcpClient_Buff.substring(a, b);
                d = TcpClient_Buff.indexOf(c) + c.length();
                e = d;
                while (int(TcpClient_Buff.length()) > e && (isdigit(TcpClient_Buff.charAt(e)) || TcpClient_Buff.charAt(e) == ch[0]))
                {
                    e++;
                }
                if (e > d)
                {
                    a = e;
                    float f = atof(TcpClient_Buff.substring(d, e).c_str());
                    Serial.print(c);
                    Serial.println(f);
                    if (c.indexOf("cm1") == 0)
                    {
                        config.cm1 = f;
                    }
                    else if (c.indexOf("cm2") == 0)
                    {
                        config.cm2 = f;
                    }
                    else if (c.indexOf("adc1") == 0)
                    {
                        config.adc1 = f;
                    }
                    else if (c.indexOf("adc2") == 0)
                    {
                        config.adc2 = f;
                    }
                    else if (c.indexOf("kpa1") == 0)
                    {
                        config.kpa1 = f;
                    }
                    else if (c.indexOf("kpa2") == 0)
                    {
                        config.kpa2 = f;
                    }
                    saveConfig();
                }
                if (e == d)
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
        if (TcpClient_Buff.indexOf("canshu") >= 0 || e > d)
        {
            sendtoTCPServer("cmd=2&uid=" + UID +
                            "&topic=" + TOPIC1 +
                            "/up&msg=canshu#" + config.cm1 +
                            "#" + config.cm2 +
                            "#" + config.adc1 +
                            "#" + config.adc2 +
                            "#" + config.kpa1 +
                            "#" + config.kpa2 + "\r\n"); // 推送消息
            delay(2000);
            sendtoUDPServer();
        }
    }
}

void sendtoUDPServer()
{
    udp.print("data=");
    udp.print(ShuiWeiValue);
    udp.print("#");
    udp.print(ShuiYaValue);
    udp.print("#");
    udp.print(ShuiWenValue);
    udp.endPacket(); // 发送数据
}
// 函数用于将多个变量相加后判断是否发生变化
bool check_and_convert_sum_change(int var1, int var2, int var3)
{
    static int prev = 0; // 静态变量
    int sum = var1 + var2 + var3;
    bool has = prev != sum;
    prev = sum;
    return has;
}

void Chuanganqi()
{
    // 读取水压值
    int sum = 0;
    for (size_t i = 1; i <= 64; i++)
    {
        // 读取ADC值
        sum += analogRead(YaliPin);
        // 计算滑动平均值
        if (i == 64)
        {
            averageValue = sum / (float)64;
            ShuiYaValue = map(averageValue, config.adc1, config.adc2, config.kpa1, config.kpa2) / (float)100;
            sum = 0;
            if (ShuiYaValue < 0.1)
            {
                ShuiYaValue = 0;
            }
            // // 将ADC平均值转换为压力值（kPa）
            // // 输出滑动平均值和压力值
            // Serial.print("滑动平均ADC值: ");
            // Serial.print(averageValue);
            // Serial.print("  压力值(kPa): ");
            // Serial.println(ShuiYaValue);
        }
    }

    // 读取超声波测距
    // 发送触发信号
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    // 读取回声信号的持续时间
    long duration = pulseIn(echoPin, HIGH, 30000);
    // 根据声速计算距离
    if (1176 < duration && duration < 30000)
    {
        Distance = duration * 0.034 / 2;
        ShuiWeiValue = map(Distance, config.cm1, config.cm2, 100, 0);
        // Serial.print("Distance: ");
        // Serial.print(Distance);
        // Serial.println(" cm");
    }

    // 60秒读取一次温度
    if (millis() - lasTemperatureReadTick >= 60000)
    {
        sensors.requestTemperatures();
        ShuiWenValue = sensors.getTempCByIndex(0);
        lasTemperatureReadTick = millis();
    }
}
void setupSystemB()
{
    pinMode(trigPin, OUTPUT);                  // 将触发引脚设置为输出
    pinMode(echoPin, INPUT);                   // 将回声引脚设置为输入
    udp.beginPacket(receiverIP, receiverPort); // 配置远端ip地址和端口
    sensors.requestTemperatures();
    ShuiWenValue = sensors.getTempCByIndex(0);
    lasTemperatureReadTick = millis();
}

void loopSystemB()
{
    static int prev = 0; // 静态变量
    if (initWiFiState && millis() - preHeartTick_B >= 500)
    {
        Chuanganqi(); // 检查增压泵状态
        if (prev++ >= 20 && check_and_convert_sum_change(ShuiWeiValue, ShuiYaValue * 100, ShuiWenValue * 100))
        {
            prev = 20;
            sendtoUDPServer(); // 发送UDP消息
            Serial.println("发送消息...");
        }
        preHeartTick_B = millis();
    }
}
